package com.agger.harmonyosthemeseditor.abilities.slices;

import com.agger.harmonyosthemeseditor.ResourceTable;
import com.agger.harmonyosthemeseditor.ThemesEditorAbility;
import com.agger.harmonyosthemeseditor.intelligent.DatabaseManager;
import com.agger.harmonyosthemeseditor.intelligent.FileManager;
import com.agger.harmonyosthemeseditor.intelligent.GeneralUtil;
import com.agger.harmonyosthemeseditor.userinterface.*;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.content.Intent;
import ohos.aafwk.content.Operation;
import ohos.agp.components.Component;
import ohos.agp.components.Switch;
import ohos.agp.components.Text;
import ohos.bundle.AbilityInfo;
import ohos.bundle.IBundleManager;
import ohos.eventhandler.EventHandler;
import ohos.eventhandler.EventRunner;
import ohos.global.configuration.DeviceCapability;
import ohos.global.resource.ResourceManager;
import ohos.miscservices.wallpaper.WallpaperController;
import ohos.system.version.SystemVersion;
import ohos.utils.IntentConstants;
import ohos.utils.net.Uri;

import java.io.File;
import java.io.FileInputStream;

public class SettingsSlice extends AbilitySlice
{

    String Dialog_Title = "爱洁羊智慧能力";
    String Dialog_Text = "停止服务后将无法使用本应用，并会退出应用。确定停止服务？";
    String Dialog_Content_StoragePermissionFailed = "存储功能被禁用，请前往应用管理页，开启主题协作器的存储权限！";
    String Dialog_Button_Cancel = "取消";
    String Dialog_Button_Accent = "停止";
    String Dialog_Button_Confirm = "好的";
    String ClearCache_Toast = "缓存已清空";
    String CommonSettings_ColorMode = "色彩模式";
    String ColorMode_Light = "浅色模式";
    String ColorMode_Dark = "深色模式";
    String ColorMode_Auto = "跟随系统";
    String ColorMode_Toast_TV = "您正在使用智慧屏产品，请勿修改色彩模式！";
    String CommonSettings_DisplayOrientation = "屏幕方向";
    String DisplayOrientation_Vertical = "竖屏显示";
    String DisplayOrientation_Horizontal = "横屏显示";
    String DisplayOrientation_Auto = "自动旋转";
    String DisplayOrientation_Toast_TV = "您正在使用智慧屏产品，请勿修改此项设置！";

    Text current_ColorMode_Text = null,current_DisplayOrientation_Text = null;
    int ColorModeItemValue = 2,DisplayOrientationItemValue = 2;
    String CurrentDialogType = "DisplayOrientation";
    RadioDialog radioDialog = null;
    RequestDialog requestDialog = null;
    public static SettingsSlice Instance;
    public boolean isOnline = false;
    EventRunner runner;

    @Override
    protected void onOrientationChanged(AbilityInfo.DisplayOrientation displayOrientation)
    {
        super.onOrientationChanged(displayOrientation);
        ReDialog();
    }

    public void ReDialog()
    {
        try
        {
            if(!radioDialog.isDestroyed)
            {
                if(!radioDialog.isShowing())
                {
                    radioDialog.destory();
                    radioDialog = null;
                    System.gc();
                }
                else
                {
                    radioDialog.destory();
                    radioDialog = null;
                    System.gc();
                    if(CurrentDialogType.equals("ColorMode"))
                        showDialog_ColorMode();
                    else
                        showDialog_DisplayOrientation();
                }
            }
        }catch (Exception ex){}
        try
        {
            if(!requestDialog.isDestroyed)
            {
                if(!requestDialog.isShowing())
                {
                    requestDialog.destory();
                    requestDialog = null;
                    System.gc();
                }
                else
                {
                    requestDialog.destory();
                    requestDialog = null;
                    System.gc();
                    showDialog_ClearCache();
                }
            }
        }catch (Exception ex){}
    }

    @Override
    public void onStart(Intent intent)
    {
        Instance = this;
        radioDialog = null;
        requestDialog = null;
        isOnline = true;
        super.onStart(intent);
        super.setUIContent(ResourceTable.Layout_slice_settings);
        //设定状态栏沉浸
        this.getWindow().setStatusBarColor(ResourceTool.getColor(this,ResourceTable.Color_dawnlighti_statusbar_normal,0xF7EDD8));
        this.getWindow().setNavigationBarColor(ResourceTool.getColor(this,ResourceTable.Color_dawnlighti_settings_bg,0xFFEBD0));
        int CurrentColorMode = getColorMode();
        if(CurrentColorMode == 0) this.getWindow().setStatusBarVisibility(0);
        else if(CurrentColorMode == 1) this.getWindow().setStatusBarVisibility(2052);
        ThemesEditorAbility.Instance.eventRunner = EventRunner.current();
        GeneralUtil.setWindowToMaxRefreshRate(getWindow());
        runner = EventRunner.current();
        DatabaseManager.Init(this);
        String mDisplayOrientation = DatabaseManager.getString("DisplayOrientation", "UNSPECIFIED");
        if(mDisplayOrientation.equals("PORTRAIT"))
            setDisplayOrientation(AbilityInfo.DisplayOrientation.PORTRAIT);
        else if(mDisplayOrientation.equals("LANDSCAPE"))
            setDisplayOrientation(AbilityInfo.DisplayOrientation.LANDSCAPE);
        else
            setDisplayOrientation(AbilityInfo.DisplayOrientation.UNSPECIFIED);
        ResourceManager resManager = getResourceManager();
        try
        {
            Dialog_Title = resManager.getElement(ResourceTable.String_Dialog_Title).getString();
            Dialog_Text = resManager.getElement(ResourceTable.String_ClearCacheDialog_Text).getString();
            Dialog_Content_StoragePermissionFailed = resManager.getElement(ResourceTable.String_Dialog_Content_StoragePermissionFailed).getString();
            Dialog_Button_Cancel = resManager.getElement(ResourceTable.String_buttoncancel).getString();
            Dialog_Button_Accent = resManager.getElement(ResourceTable.String_ClearCacheDialog_AccentButton).getString();
            Dialog_Button_Confirm = resManager.getElement(ResourceTable.String_Dialog_Button_Confirm).getString();
            ClearCache_Toast = resManager.getElement(ResourceTable.String_ClearCache_Toast).getString();
            CommonSettings_ColorMode = resManager.getElement(ResourceTable.String_CommonSettings_ColorMode).getString();
            ColorMode_Light = resManager.getElement(ResourceTable.String_ColorMode_Light).getString();
            ColorMode_Dark = resManager.getElement(ResourceTable.String_ColorMode_Dark).getString();
            ColorMode_Auto = resManager.getElement(ResourceTable.String_ColorMode_Auto).getString();
            ColorMode_Toast_TV = resManager.getElement(ResourceTable.String_ColorMode_Toast_TV).getString();
            CommonSettings_DisplayOrientation = resManager.getElement(ResourceTable.String_CommonSettings_DisplayOrientation).getString();
            DisplayOrientation_Vertical = resManager.getElement(ResourceTable.String_DisplayOrientation_Vertical).getString();
            DisplayOrientation_Horizontal = resManager.getElement(ResourceTable.String_DisplayOrientation_Horizontal).getString();
            DisplayOrientation_Auto = resManager.getElement(ResourceTable.String_DisplayOrientation_Auto).getString();
            DisplayOrientation_Toast_TV = resManager.getElement(ResourceTable.String_DisplayOrientation_Toast_TV).getString();
        }catch (Exception e){}
        Component Settings_ClearCache_Area = findComponentById(ResourceTable.Id_Settings_ClearCache);
        Component Settings_DisplayOrientation_Area = findComponentById(ResourceTable.Id_Settings_DisplayOrientation);
        Component Settings_ColorMode_Area = findComponentById(ResourceTable.Id_Settings_ColorMode);
        current_DisplayOrientation_Text = (Text) findComponentById(ResourceTable.Id_Current_DisplayOrientation_Text);
        current_ColorMode_Text = (Text) findComponentById(ResourceTable.Id_Current_ColorMode_Text);
        Settings_ClearCache_Area.setClickedListener(
                c ->
                {
                    if(radioDialog==null)
                    {
                        if(requestDialog==null)
                            showDialog_ClearCache();
                        else
                        {
                            if(!requestDialog.isDestroyed) requestDialog.destory();
                            requestDialog = null;
                            System.gc();
                            showDialog_ClearCache();
                        }
                    }
                    else
                    {
                        if(!radioDialog.isDestroyed) radioDialog.destory();
                        radioDialog = null;
                        System.gc();
                        if(requestDialog==null)
                            showDialog_ClearCache();
                        else
                        {
                            if(!requestDialog.isDestroyed) requestDialog.destory();
                            requestDialog = null;
                            System.gc();
                            showDialog_ClearCache();
                        }
                    }
                }
        );
        if(mDisplayOrientation.equals("PORTRAIT")){DisplayOrientationItemValue=0;current_DisplayOrientation_Text.setText(DisplayOrientation_Vertical);}
        else if(mDisplayOrientation.equals("LANDSCAPE")){DisplayOrientationItemValue=1;current_DisplayOrientation_Text.setText(DisplayOrientation_Horizontal);}
        else {DisplayOrientationItemValue=2;current_DisplayOrientation_Text.setText(DisplayOrientation_Auto);}
        Settings_DisplayOrientation_Area.setClickedListener
                (c ->
                {
                    //首先需要检测是否为手机或平板环境
                    int deviceType = getResourceManager().getDeviceCapability().deviceType;
                    if(deviceType == DeviceCapability.DEVICE_TYPE_PHONE || deviceType == DeviceCapability.DEVICE_TYPE_TABLET)
                    {
                        CurrentDialogType = "DisplayOrientation";
                        if(requestDialog == null)
                        {
                            if(radioDialog == null)
                                showDialog_DisplayOrientation();
                            else
                            {
                                if(!radioDialog.isDestroyed)radioDialog.destory();
                                radioDialog = null;
                                System.gc();
                                showDialog_DisplayOrientation();
                            }
                        }
                        else
                        {
                            if(!requestDialog.isDestroyed) requestDialog.destory();
                            requestDialog = null;
                            System.gc();
                            if(radioDialog == null)
                                showDialog_DisplayOrientation();
                            else
                            {
                                if(!radioDialog.isDestroyed)radioDialog.destory();
                                radioDialog = null;
                                System.gc();
                                showDialog_DisplayOrientation();
                            }
                        }
                    }
                    else
                    {
                        new GeneralToast(this).setText(DisplayOrientation_Toast_TV).show();
                    }
                });
        if(CurrentColorMode == 1){ColorModeItemValue=0;current_ColorMode_Text.setText(ColorMode_Light);}
        else if(CurrentColorMode == 0){ColorModeItemValue=1;current_ColorMode_Text.setText(ColorMode_Dark);}
        else if(CurrentColorMode == -1){ColorModeItemValue=2;current_ColorMode_Text.setText(ColorMode_Auto);}
        Settings_ColorMode_Area.setClickedListener
                (c ->
                {
                    //首先需要检测是否为手机或平板环境
                    int deviceType = getResourceManager().getDeviceCapability().deviceType;
                    if(deviceType == DeviceCapability.DEVICE_TYPE_PHONE || deviceType == DeviceCapability.DEVICE_TYPE_TABLET)
                    {
                        CurrentDialogType = "ColorMode";
                        if(requestDialog == null)
                        {
                            if(radioDialog == null)
                                showDialog_ColorMode();
                            else
                            {
                                if(!radioDialog.isDestroyed)radioDialog.destory();
                                radioDialog = null;
                                System.gc();
                                showDialog_ColorMode();
                            }
                        }
                        else
                        {
                            if(!requestDialog.isDestroyed) requestDialog.destory();
                            requestDialog = null;
                            System.gc();
                            if(radioDialog == null)
                                showDialog_ColorMode();
                            else
                            {
                                if(!radioDialog.isDestroyed)radioDialog.destory();
                                radioDialog = null;
                                System.gc();
                                showDialog_ColorMode();
                            }
                        }
                    }
                    else
                    {
                        new GeneralToast(this).setText(ColorMode_Toast_TV).show();
                    }
                });
        Switch Switch_BottomTabSlidable = (Switch)findComponentById(ResourceTable.Id_Settings_BottomTabSlidable);
        Switch_BottomTabSlidable.setChecked(MainSceneSlice.EnableBottomSlide);
        Switch_BottomTabSlidable.setCheckedStateChangedListener((button,isChecked)->
        {
            MainSceneSlice.setBottomSlidable(isChecked);
            DatabaseManager.Init(this);
            DatabaseManager.setString("EnableBottomSlide",isChecked?"Yes":"No");
        });
        Switch Switch_SuperVisionEffect = (Switch)findComponentById(ResourceTable.Id_Settings_SuperVisionController);
        Switch_SuperVisionEffect.setChecked(ThemesEditorAbility.EnableWallpaperFadeEffect);
        Switch_SuperVisionEffect.setCheckedStateChangedListener((button,isChecked)->
        {
            if(isChecked)
            {
                if (verifySelfPermission("ohos.permission.READ_USER_STORAGE") != IBundleManager.PERMISSION_GRANTED || verifySelfPermission("ohos.permission.WRITE_USER_STORAGE") != IBundleManager.PERMISSION_GRANTED)
                {
                    DatabaseManager.Init(this);
                    DatabaseManager.setString("EnableSuperVision","No");
                    ThemesEditorAbility.EnableWallpaperFadeEffect = false;
                    Switch_SuperVisionEffect.setChecked(false);
                    showPermissionRequest();
                }else
                {
                    DatabaseManager.Init(this);
                    DatabaseManager.setString("EnableSuperVision","Yes");
                    ThemesEditorAbility.EnableWallpaperFadeEffect = true;
                    ThemesEditorAbility.Instance.RebuildWallpaper();
                }
            }else
            {
                DatabaseManager.Init(this);
                DatabaseManager.setString("EnableSuperVision","No");
                ThemesEditorAbility.EnableWallpaperFadeEffect = false;
                WallpaperController wallpaperController = WallpaperController.getInstance(this);
                if(new File(getFilesDir()+"/user_wallpaper.jpg").exists())
                {
                    try{wallpaperController.setWallpaper(new FileInputStream(getFilesDir()+"/user_wallpaper.jpg"),WallpaperController.WALLPAPER_SYSTEM);}catch(Exception e){}
                }
            }
        });
        findComponentById(ResourceTable.Id_actionBar_Back).setClickedListener(c->onBackPressed());
        System.gc();
    }

    public void PermissionRouter(GeneralDialog dialog)
    {
        Intent e = new Intent();
        Operation operation = new Intent.OperationBuilder()
                .withAction(IntentConstants.ACTION_APPLICATION_DETAILS_SETTINGS)
                .withUri(Uri.getUriFromParts("package",getBundleName(),null))
                .build();
        e.setOperation(operation);
        startAbility(e);
        dialog.remove();
    }

    private void showPermissionRequest()
    {
        if (canRequestPermission("ohos.permission.READ_USER_STORAGE") && canRequestPermission("ohos.permission.WRITE_USER_STORAGE"))
            requestPermissionsFromUser(new String[]{"ohos.permission.READ_USER_STORAGE", "ohos.permission.WRITE_USER_STORAGE"}, 2);
        else
        {
            GeneralDialog.Builder builder = new GeneralDialog.Builder(getContext());
            builder.setTitle(Dialog_Title)
                    .setContent(Dialog_Content_StoragePermissionFailed)
                    .addButton(ResourceTool.getString(this,ResourceTable.String_Dialog_Button_Cancel,"取消"), GeneralButtonElement.TYPE_NORMAL, GeneralDialog::remove)
                    .addButton(Dialog_Button_Confirm, GeneralButtonElement.TYPE_ACCENT, this::PermissionRouter)
                    .setOutsideTouchClosable(false)
                    .setMovable(false)
                    .create()
                    .show();
        }
    }

    private void showDialog_ClearCache()
    {
        requestDialog = new RequestDialog(this);
        requestDialog
                .setText(Dialog_Text,true)
                .setEmptyButton(Dialog_Button_Cancel)
                .setAccentButton(Dialog_Button_Accent,c->
                {
                    try
                    {
                        String CacheDir = getContext().getCacheDir()+"";
                        FileManager.deleteDirectory(CacheDir,false,false);
                        FileManager.deleteDirectory("mnt/mdfs/account_trust/merge_view/data/com.agger.harmonyosthemeseditor",false,false);
                        new GeneralToast(this).setText(ClearCache_Toast).show();
                        requestDialog.destory();
                    }catch (Exception ex){}
                })
                .setOutsideTouchClosable(false)
                .setMovable(false)
                .show();
    }

    private void showDialog_DisplayOrientation()
    {
        try
        {
            radioDialog = new RadioDialog(this);
            radioDialog.setDestroyedListener(() ->
            {
                try
                {
                    if(radioDialog.getItemValue() == 0)
                    {
                        DisplayOrientationItemValue = 0;
                        current_DisplayOrientation_Text.setText(DisplayOrientation_Vertical);
                        DatabaseManager.Init(getContext());
                        DatabaseManager.setString("DisplayOrientation","PORTRAIT");
                        setDisplayOrientation(AbilityInfo.DisplayOrientation.PORTRAIT);
                        MainSceneSlice.Instance.setDisplayOrientation(AbilityInfo.DisplayOrientation.PORTRAIT);
                    }else if(radioDialog.getItemValue() == 1)
                    {
                        DisplayOrientationItemValue = 1;
                        current_DisplayOrientation_Text.setText(DisplayOrientation_Horizontal);
                        DatabaseManager.Init(getContext());
                        DatabaseManager.setString("DisplayOrientation","LANDSCAPE");
                        setDisplayOrientation(AbilityInfo.DisplayOrientation.LANDSCAPE);
                        MainSceneSlice.Instance.setDisplayOrientation(AbilityInfo.DisplayOrientation.LANDSCAPE);
                    }else if(radioDialog.getItemValue() == 2)
                    {
                        DisplayOrientationItemValue = 2;
                        current_DisplayOrientation_Text.setText(DisplayOrientation_Auto);;
                        DatabaseManager.Init(getContext());
                        DatabaseManager.setString("DisplayOrientation","UNSPECIFIED");
                        setDisplayOrientation(AbilityInfo.DisplayOrientation.UNSPECIFIED);
                        MainSceneSlice.Instance.setDisplayOrientation(AbilityInfo.DisplayOrientation.UNSPECIFIED);
                    }
                }catch (Exception e){}
            });
            radioDialog
                    .setTitle(CommonSettings_DisplayOrientation)
                    .setContent(new String[]{DisplayOrientation_Vertical,DisplayOrientation_Horizontal,DisplayOrientation_Auto},DisplayOrientationItemValue)
                    .setCancelText(Dialog_Button_Cancel)
                    .setOutsideTouchClosable(false)
                    .show();
        }catch (Exception e){}
    }

    private void showDialog_ColorMode()
    {
        try
        {
            radioDialog = new RadioDialog(this);
            radioDialog.setDestroyedListener(() ->
            {
                try
                {
                    if(radioDialog.getItemValue() == 0)
                    {
                        ColorModeItemValue = 0;
                        current_ColorMode_Text.setText(ColorMode_Light);
                        DatabaseManager.Init(getContext());
                        DatabaseManager.setInt("ColorMode",1);
                        if(getColorMode() != 1 && (ResourceTool.getColor(getContext(),ResourceTable.Color_dawnlighti_color_mode,-1)==-16777216))
                        {
                            if(SystemVersion.getApiVersion()>=7)
                            {
                                try
                                {
                                    findComponentById(ResourceTable.Id_root_container).setEnabled(false);
                                    new EventHandler(runner).postTask(()->{try{getAbility().restart();}catch(Exception e){}},300);
                                }catch(Exception ex){}
                            }else
                            {
                                restart();
                            }
                        }else
                            setColorMode(1);
                    }else if(radioDialog.getItemValue() == 1)
                    {
                        ColorModeItemValue = 1;
                        current_ColorMode_Text.setText(ColorMode_Dark);
                        DatabaseManager.Init(getContext());
                        DatabaseManager.setInt("ColorMode",0);
                        if(getColorMode() != 0 && (ResourceTool.getColor(getContext(),ResourceTable.Color_dawnlighti_color_mode,-16777216)==-1))
                        {
                            if(SystemVersion.getApiVersion()>=7)
                            {
                                try
                                {
                                    findComponentById(ResourceTable.Id_root_container).setEnabled(false);
                                    new EventHandler(runner).postTask(()->{try{getAbility().restart();}catch(Exception e){}},300);
                                }catch(Exception ex){}
                            }else
                            {
                                restart();
                            }
                        }else
                            setColorMode(0);
                    }else if(radioDialog.getItemValue() == 2)
                    {
                        ColorModeItemValue = 2;
                        current_ColorMode_Text.setText(ColorMode_Auto);
                        DatabaseManager.Init(getContext());
                        DatabaseManager.setInt("ColorMode",-1);
                        if(getColorMode() != -1)
                        {
                            boolean isDarkMode_BeforeChange = ResourceTool.getColor(getContext(),ResourceTable.Color_dawnlighti_color_mode,-1)==-16777216;
                            setColorMode(-1);
                            boolean isDarkMode_AfterChange = ResourceTool.getColor(getContext(),ResourceTable.Color_dawnlighti_color_mode,-1)==-16777216;
                            if(isDarkMode_AfterChange != isDarkMode_BeforeChange)
                            {
                                if(SystemVersion.getApiVersion()>=7)
                                {
                                    try
                                    {
                                        findComponentById(ResourceTable.Id_root_container).setEnabled(false);
                                        new EventHandler(runner).postTask(()->{try{getAbility().restart();}catch(Exception e){}},300);
                                    }catch(Exception ex){}
                                }else
                                {
                                    restart();
                                }
                            }
                        }
                    }
                }catch (Exception e){}
            });
            radioDialog
                    .setTitle(CommonSettings_ColorMode)
                    .setContent(new String[]{ColorMode_Light,ColorMode_Dark,ColorMode_Auto},ColorModeItemValue)
                    .setCancelText(Dialog_Button_Cancel)
                    .setOutsideTouchClosable(false)
                    .show();
        }catch (Exception e){}
    }

    @Override
    public void onBackPressed()
    {
        isOnline = false;
        DatabaseManager.Init(this);
        DatabaseManager.setString("LastAbilityName","None");
        try{getWindow().setNavigationBarColor(ResourceTool.getColor(this, ResourceTable.Color_dawnlighti_navigationbar_bottom, 0xF5F1E6));}catch (Exception ex){}
        Instance = null;
        ThemesEditorAbility.isMainSceneSlice = true;
        try{current_ColorMode_Text.release();}catch(Exception e){}
        try{current_DisplayOrientation_Text.release();}catch(Exception e){}
        current_ColorMode_Text = null;
        current_DisplayOrientation_Text = null;
        radioDialog = null;
        requestDialog = null;
        System.gc();
        if(ThemesEditorAbility.LayoutChanged)
        {
            ThemesEditorAbility.LayoutChanged = false;
            try{MainSceneSlice.Instance.restart();}catch (Exception ex){}
        }
        super.onBackPressed();
    }

    @Override
    public void onActive() {
        super.onActive();
    }

    @Override
    public void onForeground(Intent intent) {
        super.onForeground(intent);
    }
}